//  utils/request.js
import config from './config'

// 请求拦截器
const requestInterceptor = (options) => {
  // 显示加载中
  if (options.loading !== false) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
  }

  // 设置默认请求头
  const header = {
    'Content-Type': 'application/json',
    ...options.header
  }

  // 添加token
  const token = wx.getStorageSync('token')
  if (token) {
    header['Authorization'] = `Bearer ${token}`
  }

  return {
    ...options,
    header,
    url: config.baseUrl + options.url
  }
}

// 响应拦截器
const responseInterceptor = (response) => {
  // 隐藏加载中
  wx.hideLoading()

  const res = response.data

  // 处理错误
  if (res.code !== 0) {
    // token过期，重新登录
    if (res.code === 401) {
      wx.removeStorageSync('token')
      wx.navigateTo({
        url: '/pages/login/login'
      })
    } else {
      // 显示错误信息
      wx.showToast({
        title: res.msg || '请求失败',
        icon: 'none',
        duration: 2000
      })
    }
    return Promise.reject(res)
  }

  return res
}

// 错误处理
const errorHandler = (error) => {
  wx.hideLoading()
  wx.showToast({
    title: '网络错误，请稍后重试',
    icon: 'none',
    duration: 2000
  })
  return Promise.reject(error)
}

// 封装wx.request
const request = (options) => {
  // 请求拦截
  const reqOptions = requestInterceptor(options)

  return new Promise((resolve, reject) => {
    wx.request({
      ...reqOptions,
      success: (res) => {
        try {
          const result = responseInterceptor(res)
          resolve(result)
        } catch (err) {
          reject(err)
        }
      },
      fail: (err) => {
        const error = errorHandler(err)
        reject(error)
      }
    })
  })
}

// 封装get请求
const get = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'GET',
    ...options
  })
}

// 封装post请求
const post = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'POST',
    ...options
  })
}

// 封装put请求
const put = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'PUT',
    ...options
  })
}

// 封装delete请求
const del = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'DELETE',
    ...options
  })
}

module.exports = {
  request,
  get,
  post,
  put,
  delete: del
}
